package pers.qianyu.month_202011.date_20201121;

import java.util.*;

/**
 * 297. 二叉树的序列化与反序列化
 * https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
 *
 * @author mizzle rain
 * @date 2020-11-21 21:32
 */
public class Codec {
    public String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        String left = serialize(root.left);
        String right = serialize(root.right);
        return String.format("%s,%s,%s", root.val, left, right);
    }

    public TreeNode deserialize(String data) {
        String[] arr = data.split(",");
        LinkedList<String> list = new LinkedList<>(Arrays.asList(arr));
        return recur(data, list);
    }

    private TreeNode recur(String data, LinkedList<String> list) {
        if (list.isEmpty()) {
            return null;
        }
        String s = list.pollFirst();
        if ("#".equals(s)) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(s));
        node.left = recur(data, list);
        node.right = recur(data, list);
        return node;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
